package com.coffee.web.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.coffee.core.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Component
public class ResourceUtils {

	@Value("${oss.endpoint}")
    private  String endpoint;
	@Value("${oss.access-key-id}")
    private  String accessKeyId;
	@Value("${oss.access-key-secret}")
    private  String accessKeySecret;


	public byte[] downloadToBytes(String bucketName, String key) {
    	OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    	OSSObject ossObject=null;
    	// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
    	try {
    		ossObject = ossClient.getObject(bucketName, key);
    		byte[] bytes=readInputStream(ossObject.getObjectContent());
    		
    		return bytes;
    	}catch(Exception e) {
    		e.printStackTrace();
    	}finally {
    		if(ossObject!=null) {
    			try {
					ossObject.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
    		}
    		
    		ossClient.shutdown();
		}
    	
    	return null;
	}

	public byte[] readInputStream(InputStream inStream) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串  
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕  
        int len = 0;
        
        
        byte[] bytes=null;
        try {
        	//使用一个输入流从buffer里把数据读取出来  
        	while ((len = inStream.read(buffer)) != -1) {
        		//用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度  
        		outStream.write(buffer, 0, len);
        	}
        	//把outStream里的数据写入内存  
        	bytes=outStream.toByteArray();
        }catch(Exception e) {
        	e.printStackTrace();
        }finally {
        	if(outStream!=null) {
				try {
					outStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(inStream!=null) {
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
        return bytes;
    }
	
    public boolean downloadToFile(String bucketName, String key, String destFilePath) {
    	OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    	try {
    		ossClient.getObject(new GetObjectRequest(bucketName, key), new File(destFilePath));
    		
    		return true;
    	}catch(Exception e) {
    		e.printStackTrace();
    	}finally {
    		ossClient.shutdown(); 
		}
    	
    	return false;
    }


    private void getBucketList() {
    	// 创建OSSClient实例。
    	System.out.println("======getBucketList=====");
    	OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    	// 列举存储空间。
    	List<Bucket> buckets = ossClient.listBuckets();
    	System.out.println("size:"+buckets.size());
    	for (Bucket bucket : buckets) {
    	    System.out.println(" - " + bucket.getName());
    	}

    	// 关闭OSSClient。
    	ossClient.shutdown(); 
    }
    
    
    /**
     * 上传一个网上的资源到oss
     * @param bucketName
     * @param key
     * @param httpUrl
     * @return
     */
    public String upload(String bucketName, String key, String httpUrl) {
    	OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    	InputStream inputStream=null;
		try {
			inputStream = new URL(httpUrl).openStream();
			ossClient.putObject(bucketName, key, inputStream);
			inputStream.close();
			return key;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(inputStream!=null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			ossClient.shutdown();
		}
		
		return null;
    }
    
    /**
     * 上传一个字节流到OSS
     * @param bucketName
     * @param key
     * @param content
     * @return
     */
    public String upload(String bucketName, String key, byte[] content) {
		// System.out.println("======endpoint====="+endpoint+"====="+accessKeyId+"====="+accessKeySecret);
    	// 创建OSSClient实例。
    	OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
    	try {
    		ossClient.putObject(bucketName, key, new ByteArrayInputStream(content));
    		return key;
    	}catch(Exception e) {
    		e.printStackTrace();
    	}finally {
    		ossClient.shutdown();
		}
    	return null;
    }

	public String getOssUrl(String bucketName, String key) {
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
		String url = ossClient.generatePresignedUrl(bucketName, key, expiration).toString();
		String url1=url.substring(0, url.indexOf("?"));
		return url1;
	}
    /**
     * 初始化资源key
     * @return
     */
    public static String initKey(String suffix) {
    	String filename = DateUtil.date(new Date(), DateUtil.DEFAULT_DATEFULLTIME_FORMAT) + (new Random().nextInt(1000) + 9000);
        String filePath = "upload/" + DateUtil.date(new Date(), DateUtil.DEFAULT_DATE_FORMAT).replaceAll("-", "/") + "/";
        StringBuilder stringBuilder = new StringBuilder(filePath);
        stringBuilder.append(filename);
        if(StringUtils.isNotBlank(suffix)){
            stringBuilder.append(".").append(suffix);
        }
        return stringBuilder.toString();
    }


}
